//
// Created by Tan Ke on 2024/2/14.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>

int reverse(int x)
{
    char str[12] = {0};
    bool isNeg = false;
    int index = 0;
    char* minBondStr = "2147483648";
    char* maxBondStr = "2147483647";
    int result = 0;

    memset(str, 0, 12);

    if (x < 0) {
        isNeg = true;
    }

    while (x != 0) {
        str[index] = abs(x % 10) + '0';
        x = x / 10;
        index += 1;
    }

    if (strlen(str) < strlen(minBondStr)) {
        for (int i = 0; i < strlen(str); i ++) {
            result *= 10;
            result += str[i] - '0';
        }

        if (isNeg == true) {
            return -result;
        } else {
            return result;
        }
    }

    if (strlen(str) > strlen(minBondStr)) {
        return 0;
    }

    if (isNeg == false) {
        if (strncmp(str, minBondStr, strlen(minBondStr)) > 0) {
            return 0;
        }
    } else {
        if (strncmp(str, maxBondStr, strlen(maxBondStr)) > 0) {
            return 0;
        }
    }

    for (int i = 0; i < strlen(str); i ++) {
        result *= 10;
        result += str[i] - '0';
    }

    if (isNeg == true) {
        return -result;
    }
    return result;
}

int main(void)
{
    printf("%d\n", reverse(123));

    printf("%d\n", reverse(-123));

    printf("%d\n", reverse(120));

    printf("%d\n", reverse(0));
    return 0;
}